package com.kylin.common.taglib;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;

import com.kylin.common.Constants;
import com.kylin.common.entity.MsgKey;

public class MsgTag extends BodyTagSupport {
	private static MessageResources messress= MessageResources.getMessageResources("message");

	protected String locale ;
	protected String defaultMsg = "";

	public int doStartTag() throws JspException {
        /// 显示在页面的文字信息
		try {
	        String writeMess = null;
			Object msgKey = pageContext.getAttribute(Constants.MSGKEY, pageContext.REQUEST_SCOPE);
			if(msgKey instanceof MsgKey){
				String key = ((MsgKey)msgKey).getKey();
				String msg = ((MsgKey)msgKey).getDefaultMsg();
				if(messress != null){
					writeMess = messress.getMessage(getLocale(),key);
					if(writeMess == null)
						writeMess = messress.getMessage(key);
					if(writeMess == null)
						writeMess = msg;
				}
			}
			if(writeMess == null)
				writeMess = "";
			if("".equals(writeMess) && defaultMsg != null && !defaultMsg.equals(""))
				writeMess = defaultMsg;
			pageContext.getOut().println("<span class='msgTag'>"+writeMess+"</span>");
		} catch (Exception e) {
			e.printStackTrace();
			//throw new JspException(e);
		}

		////  javascript 弹出的文字信息
		try {
			Object alertMmsgKey = pageContext.getAttribute(Constants.MSGKEY_ALERT, pageContext.REQUEST_SCOPE);
			if(alertMmsgKey instanceof MsgKey){
				String key = ((MsgKey)alertMmsgKey).getKey();
				String msg = ((MsgKey)alertMmsgKey).getDefaultMsg();
				String alertInfo = null;
				if(messress != null){
					alertInfo = messress.getMessage(getLocale(),key);
					if(alertInfo == null)
						alertInfo = messress.getMessage(key);
					if(alertInfo == null)
						alertInfo = msg;
				}
				if(alertInfo != null && !alertInfo.equals("")){
					pageContext.getOut().println("<script>alert('"+alertInfo+"')</script>");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			//throw new JspException(e);
		}
		
		
		return SKIP_BODY;
	}

	private Locale getLocale(){
		HttpSession session = ((HttpServletRequest)pageContext.getRequest()).getSession();
		Object obj = session.getAttribute(Globals.LOCALE_KEY);
		if(obj instanceof Locale)
			return (Locale)obj;
		else if(locale != null && !locale.equals("")){
			return new Locale(locale);
		}else
			return pageContext.getRequest().getLocale();
	}


	public String getDefaultMsg() {
		return defaultMsg;
	}

	public void setDefaultMsg(String defaultMsg) {
		this.defaultMsg = defaultMsg;
	}

	public void setLocale(String locale) {
		this.locale = locale;
	}
}
